//This will duplicate collections before applying the changes
function duplicateAffectedCollections(collections){
    collections.forEach(function(coll){
        var collectionName = coll.getName() + "_BeforeTagChanges";
        var collectionExists = db.getCollectionNames().indexOf(collectionName) > -1
        if (!collectionExists)
        {
            coll.copyTo(collectionName);
            print("Collection " + collectionName + " created.")
        }
        else
        {
            print("Collection " + collectionName + " not created because it already exists.")
        }
    })
}

//This will overwrite the current collections with the collections copied before the deletion of tags.
function rollbackAffectedCollections(collections){
    collections.forEach(function(coll){
        var newCollectionName = coll.getName() + "_BeforeTagChanges";
        var collectionExists = db.getCollectionNames().indexOf(newCollectionName) > -1
        if (collectionExists)
        {
            coll.drop()
            print("Collection " + coll.getName() + " has been dropped.")
            db.getCollection(newCollectionName).renameCollection(coll.getName())
            print("Collection " + newCollectionName + " renamed to " + coll.getName())
        }
    })
}

function deleteTags(tags){
    var criteriaLevel2Id = db.CriteriaLevel2.findOne({Name: /Incidents/})._id;
    var criteriaLevel3Ids = db.CriteriaLevel3.find({CriteriaLevel2Id: criteriaLevel2Id, Name: { $in: tags }}).map(function(item) { return item._id; });

    db.CriteriaLevel3.remove({_id: { $in: criteriaLevel3Ids}})
    db.TemplateCriteria.remove({CriteriaLevel3Id: { $in: criteriaLevel3Ids }})
    db.FilterCriteria.remove({CriteriaLevel3Id: { $in: criteriaLevel3Ids}})
}

function deleteEventIndicators(eventIndicators){
    var criteriaLevel2Id = db.CriteriaLevel2.findOne({Name: /Events/})._id;
    var criteriaLevel3Ids = db.CriteriaLevel3.find({CriteriaLevel2Id: criteriaLevel2Id, Name: { $in: eventIndicators }}).map(function(item) { return item._id; });

    db.CriteriaLevel3.remove({_id: { $in: criteriaLevel3Ids}})
    db.TemplateCriteria.remove({CriteriaLevel3Id: { $in: criteriaLevel3Ids }})
    db.FilterCriteria.remove({CriteriaLevel3Id: { $in: criteriaLevel3Ids}})
}

var tags = [/Customer - Other/i, /Employees - Other/i]
var eventIndicators = [ /Basic Labour Standards/i ]
var affectedCollections = [db.CriteriaLevel3, db.TemplateCriteria, db.FilterCriteria];
//This function will duplicate the collections before applying the changes.
duplicateAffectedCollections(affectedCollections)

deleteTags(tags)
deleteEventIndicators(eventIndicators)

//This function will rollback the changes if it is needed
rollbackAffectedCollections(affectedCollections)
